<?php
namespace Frieza\Modules\Decorationtask\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\DecorationTask\TaskGroup;
use Doraemon\model\DecorationTask\TaskRelation;
use Doraemon\model\DecorationTask\AdminTask;
use Doraemon\model\DecorationTask\TaskVersion;
use Doraemon\tools\LinkFormat;
use PhpParser\Node\Stmt\Switch_;


class AdminTaskController extends Controller
{
    use BaseController;

    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }
    //任务列表
    public function index(Request $request,Content $content, $step){

        $request = $request->all();
        $tab = new Tab();
        $stages = TaskGroup::getGroupByTypeAndTital(TaskGroup::TYPE_STAGE, [], '', 'base');

        foreach($stages as $stage) {
            $tab->addLink($stage['group_name'], '/admin/decorationtask/admintask/'.$stage['id'], $step==$stage['id']);
        }

        $request = self::_filterWhere($request);
        return $content
            ->header('装修工具任务')
            ->breadcrumb(
                ['text' => '任务列表', 'url' => '/decorationtask/admintask/'.$step]
            )
            ->body($tab)->row(self::listAction($request, $step));
    }

    public function listAction($request = [], $step = 1){

        $limitArr = [];
        $title = $request['AND']['task_title'];
        $task_ids = TaskRelation::getInfoByGroupId($step);
        //任务数据
        $tasks = AdminTask::getTasksByIds($task_ids, $limitArr, $title);
        //用于分页总数计算
        $tasksAll = AdminTask::getTasksByIds($task_ids, [], $title);
        $groupArr = TaskRelation::getGroupIdsByTaskIds($task_ids);
        $group_ids = array_column($groupArr, 'group_id');
        $group_names = TaskGroup::getGroupNameByIds($group_ids);
        $groups = [];
        foreach($groupArr as $group_info) {
            $groups[$group_info['task_id']]['group_name'][] = $group_names[$group_info['group_id']];
        }

        foreach ($tasks as $k => $v) {
            $tasks[$k]['group_name'] = implode(',', $groups[$v['id']]['group_name']);
        }
        $gridModel = new pGridDataModel($tasks, count($tasksAll), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disablePagination();
            $grid->disableRowSelector();

            $grid->tools(function ($tools) {
                $tools->append("<a href='javascript:;' class='btn btn-sm btn-success add_version' style='float: right;' title='请在所有要修改的分组及任务都修改完后在点击发布按钮，发布后所有改动会对新使用此功能的用户生效~~,已使用此功能的老用户的任务不受影响哦'>
<i class='fa fa-save'></i>&nbsp;&nbsp;发布新版本
</a>");
                $script =
                    <<<SCRIPT
                        $('.add_version').click(function() {
                            swal({
                                title: "确认发布新版本吗？发布版本后此功能的新用户会使用新版本的任务",
                                type: "warning",
                                showCancelButton: true,
                                confirmButtonColor: "#DD6B55",
                                confirmButtonText: "确认",
                                showLoaderOnConfirm: true,
                                cancelButtonText: "取消",
                                preConfirm: function() {
                                    $.ajax({
                                        method: 'get',
                                        url: '/admin/decorationtask/admintask/publish/publish',
                                        success: function (data) {
                                            $.pjax.reload('#pjax-container');
                                            if(data.code){
                                                swal(data.msg, '', 'success');
                                            }else{
                                                swal(data.msg, '', 'error');
                                            }
                                        }
                                    });
                                }
                            });
                        });     
SCRIPT;
                Admin::script($script);
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('task_title', '任务标题')->placeholder('请输入任务标题');
                });
            });

            $grid->column('id')->sort();
            $grid->column('task_title', '任务标题');
            $grid->column('task_desc', '任务描述')->width(150);
            $grid->column('task_pre_desc', '任务详情引导文案')->width(150);
            $grid->column('group_name', '房屋信息')->replace(['1'=>'阶段', '2'=>'标签', '3'=>'房屋信息']);
            $grid->column('task_sort', '任务排序');
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '修改时间');
            $grid->column('source_id', '原始版本数据id');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableView();

                $actions->append('<a class="fa fa-superpowers reload-data" href="reclist/'.$actions->row->id.'">跳转信息</a>');
            });

        });

        $list = $listGrid->render();
        return $list;
    }

    //任务添加页面
    public function edit(Request $request,Content $content, $step, $id = 0)
    {
        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('装修工具任务')
                ->breadcrumb(
                    ['text' => '装修任务管理', 'url' => '/decorationtask/admintask/'.$step],
                    ['text' => '添加任务', 'url' => '/decorationtask/admintask/'.$step.'/create']
                )
                ->body(self::editAction($request, $step, $id , True));
        } else {
            return $content
                ->header('装修工具任务')
                ->breadcrumb(
                    ['text' => '装修任务管理', 'url' => '/decorationtask/admintask/'.$step],
                    ['text' => '添加任务', 'url' => '/decorationtask/admintask/'.$step.'/'.$id.'/edit']
                )
                ->body(self::editAction($request, $step, $id, False));
        }

    }

    public function editAction($request, $step, $id = 0, $isCreate = false)
    {
        $group_info = TaskGroup::getBaseGroupById($step);
        if(!$group_info) {
            $error = new MessageBag([
                'title' => '禁止操作非版本0的版本 且 请在分组管理中先添加阶段数据再添加任务哦'
            ]);
            return redirect('/admin/decorationtask/admintask/'.$step)->with(compact('error'));
        }

        $group_name = TaskGroup::getGroupNameByIds([$step])[$step];
        $group_swarms = TaskGroup::getGroupByType(TaskGroup::TYPE_SWARM);
        $group_swarms_arr = [];
        if($group_swarms && is_array($group_swarms)) {
            foreach($group_swarms as $group_swarm) {
                $group_swarms_arr[$group_swarm['id']] = $group_swarm['group_name'];
            }
        }
        //获取所有分组
        $group_devides = TaskGroup::getGroupByType(TaskGroup::TYPE_DEVIDE);
        $group_devides_arr = [];
        if($group_devides && is_array($group_devides)) {
            foreach($group_devides as $group_devide) {
                $group_devides_arr[$group_devide['id']] = $group_devide['group_name'];
            }
        }

        if(!$isCreate) {
            $data = AdminTask::getTaskById($id);
            $group_ids = TaskRelation::getGroupIdsByTaskIds([$id]);
            $group_ids = array_column($group_ids, 'group_id');
            $data['swarm_type'] = $group_ids;
            $data['group_tag'] = (string) TaskRelation::getInfosByTypeAndTask($id , TaskGroup::TYPE_DEVIDE)[0]['group_id'];
            $data['stage_type'] = $step;
            if(isset($data['task_rec_link_type']) && $data['task_rec_link_type']) {
                $data['task_rec_link'] = [
                    'link_type' => $data['task_rec_link_type'],
                    'link_params' => (string)$data['task_rec_link_params'],
                    'link_url' => (string)json_decode($data['task_rec_link_params'], true)['url']
                ];
            }
            $data = self::convertTips($data);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $data['stage_type'] = $step;
            $form = new Form($data);
        }

        $form->text('task_title', '任务标题')->setWidth(4, 2)->required('不能为空')->help('20字以内');
        $form->text('group_name', '所属阶段')->setWidth(4, 2)->default($group_name)->readonly();
        $form->hidden('stage_type');
        $form->multipleSelect('swarm_type', '适用房屋状态')->options($group_swarms_arr)->setWidth(4, 2)->required('不能为空');
        $form->textarea('task_desc', '任务描述')->setWidth(3, 2)->rows(3);
        $form->textarea('task_pre_desc', '任务详情引导文案')->setWidth(3, 2)->rows(3);
        if($group_devides_arr && is_array($group_devides_arr)) {
            $form->radio('group_tag', '标签')->options($group_devides_arr)->setWidth(4, 2)->help('非必选');
        }
        $form->number('task_sort', '任务排序')->setWidth(4, 2)->min(0)->required('不能为空');
        self::beforePromptTypeForm($form);

        $form->action('/admin/decorationtask/admintask/save');
        return $form->render();
    }

    //添加、修改提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        if(isset($request['id'])) {
            $data = [
                'task_title' => $request['task_title'],
                'task_desc' => $request['task_desc'],
                'task_status' => 1,
                'task_pre_desc' => $request['task_pre_desc'],
                'task_rec_desc' => (string) $request['task_rec_desc'],
                'task_rec_link_type' => (string) $request['link_type'],
                'task_rec_link_params' => (string) json_encode($request['link_params'], JSON_UNESCAPED_UNICODE),
                'task_sort' => $request['task_sort'],
                'edittime' => date('Y-m-d H:i:s', time()),
                'version' => 0,
                'admin_id' => Admin::user()->id,
            ];
            $data = self::setPromptTips($request ,$data);

            $rs = AdminTask::edit($data, $request['id']);
            if($rs) {
                //新建关系，删除旧关系
                $group_ids = TaskRelation::getInfoByTaskId([$request['id']]);
                if($group_ids && is_array($group_ids)) {
                    $relation_data['relation_status'] = TaskRelation::STATUS_DELETE;
                    $relation_data['edittime'] = date('Y-m-d H:i:s', time());
                    foreach($group_ids as $group_id) {
                        TaskRelation::edit($relation_data, $group_id);
                    }
                }

                //更新关系表
                $group_stage = [
                    'task_id' => $request['id'],
                    'group_id' => $request['stage_type'],
                    'group_type' => 1,
                    'relation_status' => 1,
                    'relation_type' => 0,
                    'relation_task_id' => 0,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'version' => 0
                ];
                TaskRelation::add($group_stage);
                if(isset($request['group_tag']) && $request['group_tag']) {
                    $group_tag = [
                        'task_id' => $request['id'],
                        'group_id' => $request['group_tag'],
                        'group_type' => 2,
                        'relation_status' => 1,
                        'relation_type' => 0,
                        'relation_task_id' => 0,
                        'addtime' => date('Y-m-d H:i:s', time()),
                        'version' => 0
                    ];
                    TaskRelation::add($group_tag);
                }
                $swarm_types = array_filter($request['swarm_type']);
                if($swarm_types && is_array($swarm_types)) {
                    foreach($swarm_types as $swarm_type) {
                        $group_swarm = [
                            'task_id' => $request['id'],
                            'group_id' => $swarm_type,
                            'group_type' => 3,
                            'relation_status' => 1,
                            'relation_type' => 0,
                            'relation_task_id' => 0,
                            'addtime' => date('Y-m-d H:i:s', time()),
                            'version' => 0
                        ];
                        TaskRelation::add($group_swarm);
                    }
                }
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
                return redirect('/admin/decorationtask/admintask/'.$request['stage_type'])->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '修改失败'
                ]);
                return redirect('/admin/decorationtask/admintask/'.$request['stage_type'])->with(compact('error'));
            }
        } else {
            $data = [
                'task_title' => $request['task_title'],
                'task_desc' => $request['task_desc'],
                'task_status' => 1,
                'task_pre_desc' => $request['task_pre_desc'],
                'task_rec_desc' => (string) $request['task_rec_desc'],
                'task_rec_link_type' => (string) $request['link_type'],
                'task_rec_link_params' => (string) json_encode($request['link_params'], JSON_UNESCAPED_UNICODE),
                'task_sort' => $request['task_sort'],
                'addtime' => date('Y-m-d H:i:s', time()),
                'edittime' => '0000-00-00 00:00:00',
                'version' => 0,
                'admin_id' => Admin::user()->id,
                'source_id' => 0,
            ];
            $rs = AdminTask::add($data);
            if($rs) {
                //更新关系表
                $group_stage = [
                    'task_id' => $rs,
                    'group_id' => $request['stage_type'],
                    'group_type' => 1,
                    'relation_status' => 1,
                    'relation_type' => 0,
                    'relation_task_id' => 0,
                    'addtime' => date('Y-m-d H:i:s', time()),
                    'version' => 0
                ];
                TaskRelation::add($group_stage);

                if(isset($request['group_tag']) && $request['group_tag']) {
                    $group_tag = [
                        'task_id' => $rs,
                        'group_id' => $request['group_tag'],
                        'group_type' => 2,
                        'relation_status' => 1,
                        'relation_type' => 0,
                        'relation_task_id' => 0,
                        'addtime' => date('Y-m-d H:i:s', time()),
                        'version' => 0
                    ];
                    TaskRelation::add($group_tag);
                }
                $swarm_types = array_filter($request['swarm_type']);
                if($swarm_types && is_array($swarm_types)) {
                    foreach($swarm_types as $swarm_type) {
                        $group_swarm = [
                            'task_id' => $rs,
                            'group_id' => $swarm_type,
                            'group_type' => 3,
                            'relation_status' => 1,
                            'relation_type' => 0,
                            'relation_task_id' => 0,
                            'addtime' => date('Y-m-d H:i:s', time()),
                            'version' => 0
                        ];
                        TaskRelation::add($group_swarm);
                    }
                }
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
                return redirect('/admin/decorationtask/admintask/'.$request['stage_type'])->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '添加失败'
                ]);
                return redirect('/admin/decorationtask/admintask/'.$request['stage_type'])->with(compact('error'));
            }
        }

    }

    //删除
    public function del($step, $id = 0)
    {
        $task_info = AdminTask::getTaskById($id);
        if($task_info['version'] != 0) {
            return response()->json([
                'status' => false,
                'message' => "禁止操作 非版本0 的版本",
            ]);
        }
        //新建关系，删除旧关系
        $group_ids = TaskRelation::getInfoByTaskId([$id]);
        if($group_ids && is_array($group_ids)) {
            $relation_data['relation_status'] = TaskRelation::STATUS_DELETE;
            $relation_data['edittime'] = date('Y-m-d H:i:s', time());
            foreach($group_ids as $group_id) {
                TaskRelation::edit($relation_data, $group_id);
            }
        }
        $data = [
            'task_status' => TaskGroup::STATUS_DELETE,
            'edittime' => date('Y-m-d H:i:s', time()),
            'admin_id' => Admin::user()->id
        ];

        $rs = AdminTask::edit($data, $id);
        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    //发布新版任务
    public function publish()
    {
        //版本表
        $version_info = [
            'addtime' => date('Y-m-d H:i:s', time()),
            'admin_id' => Admin::user()->id,
            'version_status' => TaskVersion::STATUS_NORMAL
        ];
        $version_id = TaskVersion::add($version_info);
        if($version_id) {
            //任务表
            $tasks_old = AdminTask::getTasksBase();
            if($tasks_old && is_array($tasks_old)) {
                foreach($tasks_old as $task_old) {
                    $data = [
                        'task_title' => $task_old['task_title'],
                        'task_desc' => $task_old['task_desc'],
                        'task_status' => 1,
                        'task_pre_desc' => $task_old['task_pre_desc'],

                        'task_rec_desc' => (string) $task_old['task_rec_desc'],
                        'task_rec_link_type' => (string) $task_old['task_rec_link_type'],
                        'task_rec_link_params' => (string) $task_old['task_rec_link_params'],
                        'task_rec_json' => (string) $task_old['task_rec_json'],
                        'task_sort' => $task_old['task_sort'],
                        'addtime' => date('Y-m-d H:i:s', time()),
                        'version' => $version_id,
                        'admin_id' => Admin::user()->id,
                        'finish_prompt_type' => $task_old['finish_prompt_type'],
                        'finish_prompt_json' => $task_old['finish_prompt_json'],
                        'source_id' => $task_old['id'],
                    ];
                    AdminTask::add($data);
                    $this->updateCommonVersion('task',  $data);

                }
            }
            //分组表
            $groups_old = TaskGroup::getGroupsBase();
            if($groups_old && is_array($groups_old)) {
                foreach($groups_old as $group_old) {
                    $data = [
                        'group_name' => $group_old['group_name'],
                        'group_type' => $group_old['group_type'],
                        'group_desc' => $group_old['group_desc'],
                        'group_status' => TaskGroup::STATUS_NORMAL,
                        'rela_decoration_status' => $group_old['rela_decoration_status'],
                        'group_sort' => $group_old['group_sort'],
                        'addtime' => date('Y-m-d H:i:s', time()),
                        'admin_id' => Admin::user()->id,
                        'finish_prompt_type' => $group_old['finish_prompt_type'],
                        'finish_prompt_json' => $group_old['finish_prompt_json'],
                        'is_expand' => (int) $group_old['is_expand'],
                        'is_edit_enable' => (int) $group_old['is_edit_enable'],
                        'version' => $version_id,
                        'source_id' => $group_old['id']
                    ];
                    TaskGroup::add($data);
                    $this->updateCommonVersion('group',  $data);
                }
            }
            //关系表
            $relations_old = TaskRelation::getRelationsBase();
            if($relations_old && is_array($relations_old)) {
                $groups = TaskGroup::getGroupsByVersion($version_id);
                $tasks = AdminTask::getTasksByVersion($version_id);
                foreach($relations_old as $relation_old) {
                    $group = [
                        'task_id' => $tasks[$relation_old['task_id']]['id'],
                        'group_id' => $groups[$relation_old['group_id']]['id'],
                        'group_type' => $groups[$relation_old['group_id']]['group_type'],
                        'relation_status' => 1,
                        'relation_type' => 0,
                        'relation_task_id' => 0,
                        'addtime' => date('Y-m-d H:i:s', time()),
                        'version' => $version_id
                    ];
                    TaskRelation::add($group);
                }
            }
            $data['msg'] = '发布成功';
            $data['code'] = 200;
        } else {
            $data['msg'] = '发布失败';
            $data['code'] = 0;
        }
        return $data;
    }

    public function sort(Request $request)
    {
        $params = $request->all();
        $sort = $params['sort'];
        array_walk($sort, function(&$value, $key) {
            $value = ($value+1) * 10;
        });
        if($sort && is_array($sort)) {
            foreach($sort as $sort_key=>$sort_val) {
                $data = [
                    'task_sort' => $sort_val,
                    'edittime' => date('Y-m-d H:i:s', time()),
                    'admin_id' => Admin::user()->id
                ];
                $id = $sort_key;
                AdminTask::edit($data, $id);
            }
        }
        return response()->json([
            'status' => true,
            'message' => "操作成功"
        ]);
    }

    public function recList(Request $request, Content $content, $id)
    {
        $task_info = AdminTask::getTaskById($id);

        return $content
            ->header('装修任务推荐信息配置')
            ->row($task_info['title'])
            ->body(self::reclistAction($request, $task_info));
    }

    public function reclistAction($request, $task_info)
    {
        $data = [];
        if(isset($task_info['task_rec_json']) && $task_info['task_rec_json']) {
            $data = json_decode($task_info['task_rec_json'], true);
            if($data && is_array($data)) {
                foreach($data as &$info) {
                    $info['link']['link_type'] = $info['link_type'];
                    $info['link']['link_params'] = $info['link_params'];
                }
            }

        }
        $gridModel = new pGridDataModel($data, count($data), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->column('id', 'Id');
            $grid->column('rec_id', 'rec_Id')->sort();
            $grid->column('task_rec_desc', '推荐内容文案');
            $grid->column('link', '链接信息')->linkSelect(false);
        });

        $list = $listGrid->render();
        return $list;
    }

    public function recEdit(Request $request,Content $content, $task_id, $id = 0)
    {
        $task_info = AdminTask::getTaskById($task_id);
        $request = $request->all();

        if($id == 0) {
            return $content
                ->header('装修任务推荐内容配置')
                ->row($task_info['title'])
                ->body(self::recEditAction($request, $task_id, $id , True));
        } else {
            return $content
                ->header('装修工具任务')
                ->header('装修任务推荐内容配置')
                ->row($task_info['title'])
                ->body(self::recEditAction($request, $task_id, $id, False));
        }
    }

    public function recEditAction($request, $task_id, $id = 0, $isCreate = false)
    {
        $data = [];
        $new_data = [];
        if(!$isCreate) {
            $data_json = json_decode(AdminTask::getTaskById($task_id)['task_rec_json'], true);
            if($data_json && is_array($data_json)) {
                foreach($data_json as $info) {
                    $new_data[$info['id']] = $info;
                }
            }
            $data = $new_data[$id];
            if(isset($data['link_type']) && $data['link_type']) {
                $data['link'] = [
                    'link_type' => $data['link_type'],
                    'link_params' => (string)$data['link_params']
                ];
            }
            $data['task_id'] = $task_id;
            $form = new Form($data);
            $form->hidden('id');
        } else {

            $data['task_id'] = $task_id;
            $form = new Form($data);
        }
        $form->hidden('task_id');
        $form->text('task_rec_desc', '任务列表跳转文案')->setWidth(3, 2)->required();
        $form->linkSelect('link', '任务推荐内容链接');
        $form->number('rec_sort', '推荐内容排序')->setWidth(4, 2)->min(0)->required('不能为空');
        $form->action('/admin/decorationtask/admintask/reclist/save');

        return $form->render();
    }

    public function recEditSubmit(Request $request)
    {
        $new_data = [];
        $rs_data = [];
        $request = $request->all();
        $data = [
            'task_rec_desc' => $request['task_rec_desc'],
            'link_type' => $request['link_type'],
            'link_params' => json_encode($request['link_params'], JSON_UNESCAPED_UNICODE),
            'rec_sort' => $request['rec_sort']
        ];
        //拼装json数据
        $data_json = json_decode(AdminTask::getTaskById($request['task_id'])['task_rec_json'], true);
        if ($data_json && is_array($data_json)) {
            foreach ($data_json as $info) {
                $new_data[$info['id']] = $info;
            }
        }

        if (!isset($request['id'])) {
            //追加
            $data['id'] = time();
            $data['rec_id'] = $request['task_id'].'_'.time();
            $rs_data = array_filter(array_merge($new_data, [$data]));
            $rs_sort = array_column($rs_data, 'rec_sort');
            array_multisort($rs_sort, SORT_ASC, $rs_data);
        } else {
            //修改
            $data['id'] = $request['id'];
            $data['rec_id'] = $request['task_id'].'_'.$request['id'];
            $new_data[$request['id']] = $data;
            $rs_sort = array_column($new_data, 'rec_sort');
            array_multisort($rs_sort, SORT_ASC, $new_data);
            $rs_data = $new_data;
        }
        $rs_data = json_encode(array_filter($rs_data), JSON_UNESCAPED_UNICODE);

        $rs = AdminTask::edit(['task_rec_json' => $rs_data], $request['task_id']);
        if ($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/decorationtask/admintask/reclist/' . $request['task_id'])->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/decorationtask/admintask/reclist/' . $request['task_id'])->with(compact('error'));
        }
    }

    public function recDel(Request $request, $task_id, $id)
    {
        $new_data = [];
        //拼装json数据
        $data_json = json_decode(AdminTask::getTaskById($task_id)['task_rec_json'], true);
        if($data_json && is_array($data_json)) {
            foreach($data_json as $info) {
                $new_data[$info['id']] = $info;
            }
        }
        //删除
        unset($new_data[$id]);
        $rs_sort = array_column($new_data, 'rec_sort');
        array_multisort($rs_sort, SORT_ASC, $new_data);
        $rs_data = (array)$new_data;
        $rs_data = json_encode($rs_data, JSON_UNESCAPED_UNICODE);

        $rs = AdminTask::edit(['task_rec_json'=>$rs_data], $task_id);
        if($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/decorationtask/admintask/reclist/'.$task_id)->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/decorationtask/admintask/reclist/'.$task_id)->with(compact('error'));
        }
    }


    public function updateCommonVersion($type = '' , $data = [])
    {
        $commonTasks = AdminTask::getTasksByVersion(-1);
        $commonGroups = TaskGroup::getGroupsByVersion(-1);
        $data['version'] = -1;

        switch($type) {
            case 'task':
                if(isset($commonTasks[$data['source_id']]) && is_array($commonTasks[$data['source_id']]) && $commonTasks[$data['source_id']]) {
                    $data['edittime'] = date('Y-m-d H:i:s', time());
                    AdminTask::edit($data, $commonTasks[$data['source_id']]['id']);
                } else {
                    AdminTask::add($data);
                }
                break;
            case 'group':
                if(isset($commonGroups[$data['source_id']]) && is_array($commonGroups[$data['source_id']]) && $commonGroups[$data['source_id']]) {
                    $data['edittime'] = date('Y-m-d H:i:s', time());
                    TaskGroup::edit($data, $commonGroups[$data['source_id']]['id']);
                } else {
                    TaskGroup::add($data);
                }
                break;
        }
    }
    public function recSort(Request $request)
    {
        $params = $request->all();
        $sort = $params['sort'];
        $rs = false;

        array_walk($sort, function(&$value, $key) {
            $value = ($value+1);
        });
        if($sort && is_array($sort)) {
            $new_data = [];
            $keys = array_keys($sort);
            $task_id = explode('_', $keys[0])[0];
            $data_json = json_decode(AdminTask::getTaskById($task_id)['task_rec_json'], true);
            if ($data_json && is_array($data_json)) {
                foreach ($data_json as $info) {
                    $new_data[$info['rec_id']] = $info;
                }
            }

            foreach($sort as $sort_key=>$sort_val) {
                $new_data[$sort_key]['rec_sort'] = $sort_val;
            }
            $rs_sort = array_column($new_data, 'rec_sort');
            array_multisort($rs_sort, SORT_ASC, $new_data);
            $rs_data = [];
            foreach($new_data as $data) {
                $rs_data[] = $data;
            }
            $rs_data = json_encode(array_filter($rs_data), JSON_UNESCAPED_UNICODE);
            $rs = AdminTask::edit(['task_rec_json' => $rs_data], $task_id);
        }
        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功"
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败"
            ]);
        }
    }

}